package com.borened.netty.protocol.websocket;

import com.borened.netty.protocol.http.HttpRequestDispatchHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;

@Slf4j
@Component
public class WebSocketServer implements InitializingBean {

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private int port;

    @Resource
    private WebSocketServerHandler webSocketServerHandler;

    @Override
    public void afterPropertiesSet() throws Exception {
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
    }
    public void start(int port) {
        this.port = port;
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                // 服务端可连接队列大小
                .option(ChannelOption.SO_BACKLOG, 10240)
                .childOption(ChannelOption.SO_KEEPALIVE, false)
                .option(ChannelOption.SO_REUSEADDR, true)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.SO_SNDBUF, 1024*64)
                .childOption(ChannelOption.SO_RCVBUF, 1024*64)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                //httpServer 请求解码和响应编码器的组合
                                .addLast(new HttpServerCodec())
                                //httpMessage聚合
                                .addLast(new HttpObjectAggregator(65536))
                                //websocket握手处理器
                                .addLast(new WebSocketServerProtocolHandler("/websocket"))
                                .addLast(webSocketServerHandler)
                        ;
                    }
                });
        try {
            ChannelFuture future = bootstrap.bind(port).sync();
            log.info("WebSocket Server started on port:{} " , port);
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
    }
    @PreDestroy
    public void destroy() {
        log.info("WebSocket Server stopped");
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}